import axios from 'axios';

// 温度数据项接口
export interface TemperatureDataItem {
    [field: string]: number; // 动态字段，如guilin_temp
    record_date: string; // 记录日期，格式: "YYYY-MM-DD HH:MM:SS"
}

// API响应格式
export interface TemperatureResponse {
    code: number;
    data: TemperatureDataItem[];
    message: string;
    pagination?: {
        page: number;
        page_size: number;
        total_count: number;
        total_pages: number;
    };
}

// 保持原有代码不变，增加以下新函数

// 获取预测月份的历史数据（排除当前年份）
export const getHistoricalWeatherForPredictionComparison = async (
    year: number,
    month: number,
    fields: string,
    page: number = 1,
    pageSize: number = 31
): Promise<{ [year: number]: TemperatureResponse }> => {
    try {
        // 获取前4年的历史数据
        const years = [year - 1, year - 2, year - 3, year - 4];
        const results = await Promise.all(
            years.map(async (historicalYear) => {
                const response = await axios.get(`/api/get_historical_data_by_year_and_month`, {
                    params: { year: historicalYear, month, fields, page, page_size: pageSize }
                });

                return {
                    [historicalYear]: response.data
                };
            })
        );

        return results.reduce((acc, result) => ({ ...acc, ...result }), {});
    } catch (error) {
        console.error('获取历史对比数据失败:', error);
        throw error;
    }
};

// 获取指定年份的历史天气数据（兼容原有接口）
export const getHistoricalWeatherByYear = async (
    year: number,
    fields: string,
    page: number = 1,
    pageSize: number = 366
): Promise<TemperatureResponse> => {
    try {
        const response = await axios.get(`/api/get_historical_data_by_year`, {
            params: { year, fields, page, page_size: pageSize }
        });

        // 数据验证
        if (response.data.code !== 200 || !response.data.data || response.data.data.length === 0) {
            throw new Error('未找到匹配的历史天气数据');
        }

        // 按日期排序数据
        response.data.data.sort((a, b) =>
            new Date(a.record_date).getTime() - new Date(b.record_date).getTime()
        );

        return response.data;
    } catch (error) {
        console.error('获取历史天气数据失败:', error);
        throw error;
    }
};

// 获取可用年份列表
export const getYearsList = async (): Promise<number[]> => {
    try {
        const response = await axios.get(`/api/get_available_years`);

        if (response.data.code !== 200 || !response.data.data || !Array.isArray(response.data.data)) {
            throw new Error('获取可用年份列表失败');
        }

        return response.data.data.map(Number).sort((a, b) => b - a);
    } catch (error) {
        console.error('获取可用年份列表失败:', error);
        // 出错时返回默认年份范围
        return [2025, 2024, 2023, 2022, 2021];
    }
};

// 获取可用月份列表（基于指定年份）
export const getMonthsListByYear = async (year: number): Promise<number[]> => {
    try {
        const response = await axios.get(`/api/get_available_months`, {
            params: { year }
        });

        if (response.data.code !== 200 || !response.data.data || !Array.isArray(response.data.data)) {
            throw new Error('获取可用月份列表失败');
        }

        return response.data.data.map(Number).sort((a, b) => a - b);
    } catch (error) {
        console.error('获取可用月份列表失败:', error);
        // 出错时返回完整月份列表
        return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    }
};

// 获取历史温度数据统计信息
export const getHistoricalTemperatureStats = async (
    startYear: number,
    endYear: number,
    field: string = 'guilin_max'
): Promise<{
    yearlyAverages: { year: number; average: number }[];
    allTimeMax: number;
    allTimeMin: number;
}> => {
    try {
        const response = await axios.get(`/api/get_historical_temperature_stats`, {
            params: { start_year: startYear, end_year: endYear, field }
        });

        if (response.data.code !== 200 || !response.data.data) {
            throw new Error('获取历史温度统计信息失败');
        }

        return response.data.data;
    } catch (error) {
        console.error('获取历史温度统计信息失败:', error);
        throw error;
    }
};  